package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishFlavorMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public R saveWithFlavor(DishDto dishDto) {
        if (dishDto == null) {
            return R.error("非法参数");
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto, dish);
        dishMapper.insert(dish);
        //  一个dishdto 可能对应多个 flavor    一对多
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dish.getId());
            dishFlavorMapper.insert(flavor);
        }
        return R.success("添加成功");
    }

    @Override
    public R findPage(Integer page, Integer pageSize, String name) {
        IPage<Dish> p = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> wp = new LambdaQueryWrapper<>();
        if (name != null) {
            wp.like(Dish::getName, name);
        }
        IPage<Dish> dishIPage = dishMapper.selectPage(p, wp);
/*        List<Dish> records = dishIPage.getRecords();
        String jsonString = JSON.toJSONString(records);
        List<DishDto> dishDtos = JSON.parseArray(jsonString, DishDto.class);
        dishDtos.forEach(c -> {
            Category category = categoryMapper.selectById(c.getCategoryId());
            c.setCategoryName(category.getName());
        });
        String jsonString1 = JSON.toJSONString(dishIPage);
        Page dishDtoPage = JSON.parseObject(jsonString1, Page.class);
        dishDtoPage.setRecords(dishDtos);*/

        ArrayList<DishDto> dishDtos = new ArrayList<>();
        List<Dish> dishList = dishIPage.getRecords();
        for (Dish dish : dishList) {
            Long categoryId = dish.getCategoryId();
            Category category = categoryMapper.selectById(categoryId);
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            dishDto.setCategoryName(category.getName());
            dishDtos.add(dishDto);
        }
        Page<DishDto> dishDtoPage = new Page<>();
        dishDtoPage.setRecords(dishDtos);
        dishDtoPage.setCurrent(dishIPage.getCurrent());
        dishDtoPage.setSize(dishIPage.getSize());
        dishDtoPage.setPages(dishIPage.getPages());
        dishDtoPage.setTotal(dishIPage.getTotal());

        return R.success(dishDtoPage);
    }

    @Override
    public R findById(Long id) {
        Dish dish = dishMapper.selectById(id);
        LambdaQueryWrapper<DishFlavor> warpper = new LambdaQueryWrapper<>();
        warpper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(warpper);
        //  封装到dshdto
        // 将dish 转换成dishdto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(dishFlavorList);
        return R.success(dishDto);
    }

    @Override
    public R updateByDishId(DishDto dishDto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto, dish);
        dishMapper.updateById(dish);
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dish.getId());
        dishFlavorMapper.delete(wrapper);
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
            dishFlavorMapper.insert(flavor);
        }
        return R.success("修改成功");
    }

    @Transactional
    @Override
    public R delete(Long[] ids) {
        if (ids == null) {
            return R.error("参数为空");
        }
        /**  for (Long id : ids) {
         dishMapper.deleteById(id);
         }  这里不使用遍历删除 因为逐个删除,如果某一个删除失败,就需要回滚之前全部的
         */
        //  删除菜品
        dishMapper.deleteBatchIds(Arrays.asList(ids));
        // 删除菜品同时删除口味
        LambdaUpdateWrapper<DishFlavor> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(DishFlavor::getDishId, ids);
        dishFlavorMapper.delete(wrapper);
        return R.success("删除成功");
    }

    @Override
    public R status(Integer id, Long[] ids) {
 /*       for (Long aLong : ids) {
            Dish dish = dishMapper.selectById(aLong);
            dish.setStatus(id);
            dishMapper.updateById(dish);
        }*/
        Dish dish = new Dish();
        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Dish::getStatus, id).in(Dish::getId, ids);
        dishMapper.update(dish, wrapper);
        return R.success("成功");
    }

    @Override
    public R findAll(Long categoryId) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, categoryId);
        List<Dish> dishList = dishMapper.selectList(wrapper);
        String s = JSON.toJSONString(dishList);
        List<DishDto> dishDtos = JSON.parseArray(s, DishDto.class);
        for (DishDto dishDto : dishDtos) {
            LambdaQueryWrapper<DishFlavor> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(DishFlavor::getDishId, dishDto.getId());
            List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(wrapper2);
            dishDto.setFlavors(dishFlavorList);
        }
        return R.success(dishDtos);
    }
}
